import Handler from "./Handler";

export default class Context {

    private static _context: Context = new Context()

    static get(): Context {
        return Context._context
    }

    private cmdHandlers = {}
    private cmdInterceptors: Handler[] = []

    sendMessage(message: string, ...args: any[]) {
        let coms = <any[]>Context.get().cmdHandlers[message]
        if (!coms  || coms.length <= 0) {
            console.warn(`没有找到注册此消息的组件:${message}, 请检查消息是否拼写错误`)
            return
        } else {
            //检测是否有拦截组件将消息处理了.
            for (let i = 0; i < this.cmdInterceptors.length; i++) {
                if (this.cmdInterceptors[i].handleMessage(message, args)) return
            }

            let ret = false
            for (let i = 0; i < coms.length; i++) {
                ret = coms[i].handleMessage(message, args)
                if (ret) {
                    cc.log(`消息:${message},被组件 ${coms[i]} 拦截,不再向下传递.`)
                    break
                }
            }
        }
    }

    //将某些消息注册在某组件上.当有人发送此消息时,组件将被通知.
    register(com: Handler, ...messages: string[]) {
        for (let i = 0; i < messages.length; i++) {
            let message = messages[i]
            let coms = <Handler[]>this.cmdHandlers[message]
            if (!coms) {
                coms = []
                coms.push(com)
                this.cmdHandlers[message] = coms
            } else {
                let index = coms.indexOf(com)
                if (index == -1) {
                    coms.push(com)
                }
            }
        }
    }

    //从组件上删除某些已注册的消息.
    unregister(com: Handler, ...message: string[]) {
        if (message == null || message.length <= 0) return

        for (let i = 0; i < message.length; i++) {
            let coms = <Handler[]>this.cmdHandlers[message[i]]
            if (!coms || coms.length <= 0) continue
            let index = coms.indexOf(com)
            if (index == -1) return
            coms.splice(index, 1)
        }
    }

    addInterceptor(com: Handler) {
        if (this.cmdInterceptors.indexOf(com) != -1) return
        this.cmdInterceptors.push(com)
    }
}

